<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message, Notification } from '@arco-design/web-vue'
import ConflictTip from './ConflictTip.vue'
import { ClassInfoApi } from '@/apis'
import { useForm } from '@/hooks'
import ProFormPanel from '@/components/ProForm/ProFormPanel.vue'
import EmployeeSelect from '@/views/system/employee/EmployeeSelect.vue'
import ArrangeTemplatePicker from '@/views/system/business/rules/ArrangeTemplate/ArrangeTemplatePicker.vue'
import TimeTemplatePicker from '@/views/system/business/rules/TimeTemplate/TimeTemplatePicker.vue'
import ArrangeCalendar from '@/views/system/business/rules/ArrangeTemplate/components/ArrangeCalendar.vue'

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const formKey = ref(0)

const formRef = ref<FormInstance>()
const arrangePickerRef = ref<InstanceType<typeof ArrangeTemplatePicker>>()
const timePickerRef = ref<InstanceType<typeof TimeTemplatePicker>>()

const classId = ref<string>('')
// 排课日历
const calendarRef = ref<InstanceType<typeof ArrangeCalendar>>()
const lessonList = ref<any[]>([])

const { form, resetForm } = useForm({
  campudId: undefined,
  classroomId: undefined,
  leadTeacherId: undefined,
  arrangeTemplateId: undefined,
  timeTemplateId: undefined,
})

const rules: FormInstance['rules'] = {
  classroomId: [{ required: true, message: '请选择教室' }],
  leadTeacherId: [{ required: true, message: '请选择主讲老师' }],
}

// 排课期段
const selectedArrangeTemplate = ref()
const onArrangeTemplateSelected = (record) => {
  form.arrangeTemplateId = record.id
  selectedArrangeTemplate.value = record
}

// 排课时间段
const selectedTimeTemplate = ref()
const onTimeTemplateSelected = (record) => {
  form.timeTemplateId = record.id
  selectedTimeTemplate.value = record
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  selectedArrangeTemplate.value = ''
  selectedTimeTemplate.value = ''
  resetForm()
}

// 打开新增
const open = async (id: string) => {
  classId.value = id
  loading.value = false
  reset()
  formKey.value += 1 // 更新 key，强制重新挂载组件
  visible.value = true
}

// 预排课
const scheduleLoading = ref(false)
const getClassShecdule = async () => {
  scheduleLoading.value = true
  try {
    const req: ClassInfoApi.ClassScheduleReq = {
      leadTeacherId: form.leadTeacherId,
      campusId: form.campusId,
      classroomId: form.classroomId,
      arrangeTemplateId: form.arrangeTemplateId,
      timeTemplateId: form.timeTemplateId,
    }
    const classScheduleList = await ClassInfoApi.generateShecdule(req)
    lessonList.value = (classScheduleList || []).map((item: any) => {
      return {
        lessonStartTime: item.lessonStartTime.split(' ')[1],
        lessonEndTime: item.lessonEndTime.split(' ')[1],
        lessonDate: new Date(item.lessonDate),
        lessonIndex: item.lessonIndex,
        conflictInfo: item.conflictInfo,
      }
    })
  } finally {
    scheduleLoading.value = false
  }
}

// 自动排课
watchEffect(() => {
  if (form.arrangeTemplateId && form.timeTemplateId && form.classroomId && form.leadTeacherId) {
    getClassShecdule()
  }
})

// 保存
const onSave = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) {
      return false
    }
    if (classId.value === '' || classId.value === undefined) {
      Notification.error('出错了，请重新进入页面')
      return false
    }
    await ClassInfoApi.reschedule(form, classId.value)
    Message.success('重新排课成功')
    emit('change')
    visible.value = false
  } catch {
    return false
  }
}

defineExpose({ open })
</script>

<template>
  <ProFormPanel
    :key="formKey"
    v-model:visible="visible"
    mode="modal"
    :max-width="960"
    title="排课信息"
    :loading="loading"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules>
      <a-row :gutter="40">
        <a-col :span="12">
          <a-form-item label="教室" field="classroomId">
            <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" placeholder="请选择教室" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="主讲老师" field="leadTeacherId">
            <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="请选择老师" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-space class="mb" size="large">
        <a-button type="primary" @click="arrangePickerRef?.open()">
          上课期段
          <span v-if="selectedArrangeTemplate" class="mr-1">:{{ selectedArrangeTemplate.name }}</span>
          <icon-down />
        </a-button>
        <a-button type="primary" @click="timePickerRef?.open()">
          上课时间段
          <span v-if="selectedTimeTemplate" class="mr-1">:{{ selectedTimeTemplate.name }}</span>
          <icon-down />
        </a-button>
        <a-alert v-if="selectedArrangeTemplate">
          <a-space>
            <span class="text-black">{{ selectedArrangeTemplate.classYear }}年 · <DictLabel v-model="selectedArrangeTemplate.term" code="TermEnum" /> · <DictLabel v-model="selectedArrangeTemplate.grade" code="Grade" /></span>
            <span class="text-13px text-gray-6">
              {{ selectedArrangeTemplate.startDate }}~{{ selectedArrangeTemplate.endDate }}
            </span>
            <span v-if="selectedTimeTemplate" class="text-13px text-gray-6">
              {{ selectedTimeTemplate.startTime }} - {{ selectedTimeTemplate.endTime }}
            </span>
          </a-space>
        </a-alert>
      </a-space>

      <div v-if="scheduleLoading" class="my flex-row-center-center">
        <a-spin dot tip="课表重新生成中..." />
      </div>
      <ArrangeCalendar
        v-if="lessonList && lessonList.length > 0"
        ref="calendarRef"
        v-model="lessonList"
        select-mode="select"
        :disabled="true"
        :show-dot="false"
        :readonly="true"
      >
        <template #extra="{ item }">
          <div v-if="item.conflictInfo" class="icon">
            <a-popover title="冲突课次">
              <a-tag color="red">
                <template #icon>
                  <icon-exclamation-circle-fill />
                </template>
                冲突
              </a-tag>
              <template #content>
                <ConflictTip :data="item.conflictInfo" />
              </template>
            </a-popover>
          </div>
          <div v-else class="icon color-green">
            <icon-check-circle-fill />
          </div>
        </template>
      </ArrangeCalendar>
    </a-form>
    <ArrangeTemplatePicker ref="arrangePickerRef" @select="onArrangeTemplateSelected" />
    <TimeTemplatePicker ref="timePickerRef" @select="onTimeTemplateSelected" />
  </ProFormPanel>
</template>

<style lang="less" scoped></style>
